package com.hw.one.dam2.dao;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.entity.WaterSurfaceEntity;
import com.hw.one.dam2.param.PollutionIndustryParam;

@Repository(value = "waterSurfaceDao")
public class WaterSurfaceDao implements IWaterSurfaceDao {

	// 在Spring中注册的 mongoDB Template
	@Autowired
	private MongoTemplate mongoTemplateStandardSiteData;

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map> findWaterSurfaceNewHourDataByPSCode(List<String> siteCodeList) throws Exception {
		Map newData = mongoTemplateStandardSiteData.findOne(new Query(Criteria.where("SITECODE").in(siteCodeList))
				.with(new Sort(Sort.Direction.DESC, "MONITORTIME")), Map.class, "T_DATA_WATERSURFACE_HOUR_S_COLLECT");

		if (null == newData) {
			return null;
		}

		Object timeObj = newData.get("MONITORTIME");

		// 查询条件 增加时间查询条件
		Criteria criteria = Criteria.where("MONITORTIME").is(timeObj);
		criteria.and("SITECODE").in(siteCodeList);

		Query query = new Query(criteria);
		query.with(new Sort(Sort.Direction.DESC, "MONITORTIME"));

		List<Map> ipList = mongoTemplateStandardSiteData.find(query, Map.class, "T_DATA_WATERSURFACE_HOUR_S_COLLECT");

		return ipList;
	}

	@Override
	public List<WaterSurfaceEntity> findWaterSurfaceDataByPSCode(PollutionIndustryParam paramPO, String collectionName)
			throws Exception {
		String startTime = paramPO.getStartTime();
		String endTime = paramPO.getEndTime();
		// 查询条件 增加时间查询条件
		Criteria criteria = Criteria.where("MONITORTIME");

		criteria.gte(startTime).lte(endTime);
		criteria.and("SITECODE").in(paramPO.getPSCodeList());

		// 创建查询对象
		Query query = new Query(criteria);
		query.with(new Sort(Sort.Direction.DESC, "MONITORTIME"));
		List<WaterSurfaceEntity> ipList = mongoTemplateStandardSiteData.find(query, WaterSurfaceEntity.class,
				collectionName);

		return ipList;
	}

	@Override
	public List<WaterSurfaceEntity> findWaterSurfaceLast12HourDataBySiteCode(String siteCode) {
		// 查询条件 增加时间查询条件
		Criteria criteria = Criteria.where("SITECODE").is(siteCode);

		// 创建查询对象
		Query query = new Query(criteria);
		query.with(new Sort(Sort.Direction.DESC, "MONITORTIME")).limit(12);
		List<WaterSurfaceEntity> ipList = mongoTemplateStandardSiteData.find(query, WaterSurfaceEntity.class,
				"T_DATA_WATERSURFACE_HOUR_S_COLLECT");
		
		// 把时间按照正序排序
		Collections.reverse(ipList);
		
		return ipList;
	}

}
